﻿//  --------------------------------
//  Copyright (c) 2010 Michael Schuler, Sascha Burger. All rights reserved.
//  This source code is made available under the terms of the Microsoft Public License (Ms-PL)
//  http://p2pmessaging.codeplex.com/license
//  ---------------------------------
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using p2pMessaging.Interfaces;

namespace p2pMessaging.BL
{
	/// <summary>
	/// Service to serialize and deserialize objects.
	/// </summary>
	public sealed class SerializeService : ISerializeService
	{
		/// <summary>
		/// Serialize an object of type <see cref="T"/> to a byte array.
		/// </summary>
		/// <typeparam name="T">Type of <paramref name="obj"/></typeparam>
		/// <param name="obj">Object to serialize</param>
		/// <returns>byte array</returns>
		public byte[] Serialize<T>(T obj)
		{
			using (MemoryStream stream = new MemoryStream())
			{
				BinaryFormatter formatter = new BinaryFormatter();
				formatter.Serialize(stream, obj);
				stream.Position = 0;
				byte[] buffer = new byte[stream.Length];
				stream.Read(buffer, 0, buffer.Length);
				return buffer;
			}
		}

		/// <summary>
		/// Deserialize a byte array to an object of type <see cref="T"/>.
		/// </summary>
		/// <typeparam name="T">Type of the return value.</typeparam>
		/// <param name="obj">byte array</param>
		/// <returns>Object of type <see cref="T"/>.</returns>
		public T Deserialize<T>(byte[] obj)
		{
			using (MemoryStream stream = new MemoryStream(obj))
			{
				BinaryFormatter formatter = new BinaryFormatter();
				return (T)formatter.Deserialize(stream);
			}
		}
	}
}
